package com.handpay.framework.utils;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PermissionInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.content.PermissionChecker;
import android.util.ArrayMap;
import android.util.Log;
import android.widget.Toast;

import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.base.activity.BaseActivity;
import com.handpay.zztong.hp.log.HPLog;

import java.util.ArrayList;

/**
 * Created by fplei on 2017/3/9.
 * 主要是检查用户是否赋予应用权限（一下权限在6.0需要动态申请）
 * 获取位置信息：
    Manifest.permission.ACCESS_COARSE_LOCATION
    Manifest.permission.ACCESS_FINE_LOCATION
 读写SD卡：
    Manifest.permission.READ_EXTERNAL_STORAGE
    Manifest.permission.WRITE_EXTERNAL_STORAGE
 获取手机状态：
    Manifest.permission.READ_PHONE_STATE
 相机权限：
    Manifest.permission.CAMERA
 音频权限
    Manifest.permission.RECORD_AUDIO
 读写sd卡权限：
    WRITE_EXTERNAL_STORAGE
    MOUNT_UNMOUNT_FILESYSTEMS  在SDCard中创建与删除文件权限
    READ_EXTERNAL_STORAGE
 获取日志权限：
    READ_LOGS
 呼出电话权限：
    CALL_PHONE
 读取和写入系统设置权限
    READ_SETTINGS
    WRITE_SETTINGS
 */

public class PermissionCheckUtil {

    public static final int requestPerssionsCode=101010;

    /**
     * 检查是否可以使用某个权限
     * @param mcontext
     * @param permissions 检查的权限
     *
     */
    public static void checkPerssion(final BaseActivity mcontext, final String permissions){
        boolean result = true;
        //>=6.0系统对百度地图权限进行动态弹窗
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // For Android < Android M, self permissions are always granted.
            ArrayMap<String,String> permissionInfos=new ArrayMap<>();
            permissionInfos.put(Manifest.permission.ACCESS_COARSE_LOCATION,"访问设备位置");
            permissionInfos.put(Manifest.permission.ACCESS_FINE_LOCATION,"访问设备位置");
            permissionInfos.put(Manifest.permission.CAMERA,"访问设备相机");
            permissionInfos.put(Manifest.permission.RECORD_AUDIO,"访问录音设备");
            permissionInfos.put(Manifest.permission.READ_PHONE_STATE,"访问手机状态");
            permissionInfos.put(Manifest.permission.WRITE_EXTERNAL_STORAGE,"写入外部设置");
            permissionInfos.put(Manifest.permission.READ_EXTERNAL_STORAGE,"读取外部设置");
            permissionInfos.put(Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS,"访问SDCard设备");
            permissionInfos.put(Manifest.permission.CALL_PHONE,"拨打电话");
            try {
                PackageInfo info = mcontext.getPackageManager().getPackageInfo(mcontext.getPackageName(), 0);
                final String appname=info.applicationInfo.loadLabel(mcontext.getPackageManager()).toString();
                int targetSdkVersion = info.applicationInfo.targetSdkVersion;
                com.handpay.zztong.hp.log.HPLog.i(com.handpay.zztong.hp.log.HPLog.TAG_RESULT,"targetSdkVersion:"+targetSdkVersion);
                if (targetSdkVersion >= Build.VERSION_CODES.M) {
                    // targetSdkVersion >= Android M, we can
                    // use Context#checkSelfPermission
                    result = mcontext.checkSelfPermission(permissions)== PackageManager.PERMISSION_GRANTED;
                } else {
                    // targetSdkVersion < Android M, we have to use PermissionChecker
                    //建议targetSdkVersion使用23或以上，否则不能呢个弹窗让用户开启权限
                    result = PermissionChecker.checkSelfPermission(mcontext, permissions)== PermissionChecker.PERMISSION_GRANTED;
                }
                /*PackageInfo pack =mcontext.getPackageManager().getPackageInfo(mcontext.getPackageName(),PackageManager.GET_PERMISSIONS);
                String[] apppermissions = pack.requestedPermissions;
                if(permissions != null){
                    for(String str : apppermissions){
                        PermissionInfo permissionInfo = mcontext.getPackageManager().getPermissionInfo(str, 0);
                        permissionInfos.put(permissionInfo.name,permissionInfo.loadLabel(mcontext.getPackageManager()).toString());
//                        Log.i("result","describeContents:"+permissionInfo.loadDescription(pm)+";name:"+permissionInfo.name+";lable:"+ permissionInfo.loadLabel(pm));
                    }
                }*/
                if(!result){
                    //如检查到无权限提升用户赋予权限
                    com.handpay.zztong.hp.log.HPLog.i(com.handpay.zztong.hp.log.HPLog.TAG_RESULT,"-----requestPermissions-----");
                    //反正用户误选永久禁止，提示用户
                    if (!mcontext.shouldShowRequestPermissionRationale(permissions)){
                        String temp_=null;
                        if(permissionInfos.containsKey(permissions)){
                            temp_=appname+"“"+permissionInfos.get(permissions)+"”权限被永久禁止，请在设置页面手动开启！";
                        }
                        mcontext.showAlertDialog(mcontext, mcontext.getString(R.string.tip),temp_, false, "确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
//                                mcontext.requestPermissions(new String[] {permissions},requestPerssionsCode);
                                //跳转应用管理界面 ACTION_APPLICATION_SETTINGS
                                Intent intent =  new Intent(Settings.ACTION_SETTINGS);
                                mcontext.startActivity(intent);
                                dialog.dismiss();
                            }
                        }, "取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        return;
                    }
                    mcontext.requestPermissions(new String[]{permissions},requestPerssionsCode);
                }
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

}
